.PHONY: clean rebuild update-deps tests help docker docker-tests docker-publish

NAME := php-malware-finder
TAG_COMMIT := $(shell git rev-list --abbrev-commit --all --max-count=1)
VERSION := $(shell git describe --abbrev=0 --tags --exact-match $(TAG_COMMIT) 2>/dev/null || true)
IMAGE_VERSION := $(VERSION)
DATE := $(shell git log -1 --format=%cd --date=format:"%Y%m%d%H%M")
ifeq ($(VERSION),)
    VERSION := $(DATE)
    IMAGE_VERSION := latest
endif
LDFLAGS := "-X main.version=$(VERSION)"
GO_FLAGS := -o $(NAME) -ldflags $(LDFLAGS)
IMAGE_REGISTRY := ghcr.io
IMAGE_REGISTRY_USER := jvoisin
IMAGE_NAME := $(IMAGE_REGISTRY)/$(IMAGE_REGISTRY_USER)/$(NAME)

all: php-malware-finder

php-malware-finder: ## Build application
	@go build $(GO_FLAGS) .

clean: ## Delete build artifacts
	@rm -f $(NAME)

rebuild: clean all ## Delete build artifacts and rebuild

update-deps: ## Update dependencies
	@go get -u .
	@go mod tidy -v

tests: php-malware-finder ## Run test suite
	@bash ./tests.sh

docker: ## Build docker image
	docker pull $(IMAGE_NAME):latest || true
	docker build --pull --cache-from=$(IMAGE_NAME):latest -t $(IMAGE_NAME):latest .
	docker tag $(IMAGE_NAME):latest $(IMAGE_NAME):$(IMAGE_VERSION)

docker-tests: ## Run docker image against the samples folder
	@(docker run --rm -v $(shell pwd)/data/samples:/data $(IMAGE_NAME):latest && exit 1) || (test $$? -eq 255 || exit 1)

docker-publish: ## Push docker image to the container registry
	@docker push $(IMAGE_NAME):latest
	@(test "$(IMAGE_VERSION)" != "latest" && docker push $(IMAGE_NAME):$(IMAGE_VERSION)) || true

help: ## Show this help
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
